﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json;

using tcm.entity;
using tcm.response;

namespace tcm.utils
{
    public class WeChatSendMessage
    {
        public static readonly WeChatSendMessage Instance;
        static WeChatSendMessage()
        {
            Instance = new WeChatSendMessage();
        }

        public string OrderSupplyNotice(long order_id)
        {
            if (order_id<=0)
                return "订单编号不能为空";

            var data = GCCEntrance.DBManager!.LocalDB!.Select<Order, User, Cabinet>()
                    .InnerJoin((o, u,c) => o.user_id==u.id&&o.cabinet_id==c.id)
                    .Where((o, u,c) => o.id==order_id)
                    .First((order, user, cabinet) => new { order, user, cabinet });
            if (data==null)
                return "订单编号不存在";

            var user = GCCEntrance.DBManager!.LocalDB!.Select<User>()
                  .Where(u => u.id==data.order.delivery_id)
                  .First();

            var uesrPhmList = GCCEntrance.DBManager!.LocalDB!.Select<UesrPhmList, Pharmaceutical>()
                .LeftJoin((u, p) => u.phm_id==p.id)
               .Where((u, p) => u.order_id==data.order.id&&u.phm_list_id==data.cabinet.phm_list_id)
               .ToList((u, p) => new { u, p });

            var phmStr =new StringBuilder();
            foreach (var item in uesrPhmList)
                _=phmStr.Append(string.Format("{0}{1}件", item.p.pname,item.u.num));

            var dataTemplate = new DataTemplate();
            dataTemplate.first.value = "您的物品已成功存入智能货柜";
            dataTemplate.keyword1.value = user?.uname;
            dataTemplate.keyword2.value = phmStr.ToString();
            dataTemplate.keyword3.value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            dataTemplate.keyword4.value = string.Format("{0}号货架{1}号箱格", data.cabinet.container_no,data.cabinet.cabinet_no);
            dataTemplate.remark.value ="感谢您的使用。";

            var temp = new WeChatTemplate()
            {
                template_id=GlobalConstant.UserTemplateId,
                touser=data.user.wx_id,
                url="",
                data=dataTemplate
            };

            return SendMessage(temp);
        }


        public  string SupplyOrderNotice(long order_id)
        {
            if (order_id<=0)
                return "订单编号不能为空";

            var data = GCCEntrance.DBManager!.LocalDB!.Select<Order, User, Cabinet>()
                    .InnerJoin((o, u, c) => o.delivery_id==u.id&&o.cabinet_id==c.id)
                    .Where((o, u, c) => o.id==order_id)
                    .First((order, user, cabinet) => new { order, user, cabinet });
            if (data==null)
                return "订单编号不存在";


            var dataTemplate = new DataTemplate();
            dataTemplate.first.value = "配送订单";
            dataTemplate.keyword1.value = data.order.id.ToString();
            dataTemplate.keyword2.value = GetOrderStatus(data.order.status);
            dataTemplate.remark.value ="请及时配送";

            var temp = new WeChatTemplate()
            {
                template_id=GlobalConstant.DeliveryTemplateId,
                touser=data.user.wx_id,
                url="",
                data=dataTemplate
            };

            return SendMessage(temp);
        }



        /// <summary>
        /// 发送消息
        /// </summary>
        private  string SendMessage(WeChatTemplate weChatTemplate)
        {
            string msg = string.Empty;
          
            try
            {
                StringBuilder strToken = new StringBuilder();
                var parameter = string.Format("appid={0}&secret={1}&grant_type={2}", GlobalConstant.Appid, GlobalConstant.AppSecret, "client_credential");
                _=strToken.Append(GlobalConstant.WeChatTokenUrl+"?"+parameter);

                var tokenResponse = HttpHelper.Instance.GetAsync(url: strToken.ToString()).Result;
                if (tokenResponse.IsSuccessStatusCode)
                {
                    var resToken = tokenResponse.Content.ReadAsStringAsync().Result;
                    var weChatToken = JsonConvert.DeserializeObject<WeChatTokenRes>(resToken);
                    if (!string.IsNullOrWhiteSpace(weChatToken.access_token))
                    {
                        string url = string.Format("{0}?access_token={1}", GlobalConstant.WeChatSendMessageUrl, weChatToken.access_token);
                        var sendResponse = HttpHelper.Instance.PostAsync<WeChatTemplate>(url, weChatTemplate).Result;
                        if (sendResponse.IsSuccessStatusCode)
                        {
                            var sendRes = sendResponse.Content.ReadAsStringAsync().Result;
                            var result = JsonConvert.DeserializeObject<WeChatSendRes>(sendRes);
                            if (!result.errcode.Equals("0"))
                                throw new Exception(sendRes);
                        }
                    }
                    else
                        throw new Exception(resToken);
                }
            }
            catch (Exception exc)
            {
                msg="接口返回异常："+ exc;
            }
            return msg;
        }


        private  string GetOrderStatus(int status)
        {
            var str = string.Empty;
            switch (status)
            {

                case 0:
                    str="未完成";
                    break;
                case 1:
                    str="已完成";
                    break;
                case 2:
                    str="待配送";
                    break;
                case 3:
                    str="配送中";
                    break;
                case 4:
                    str="配送完成";
                    break;
                default:
                    break;
            }
            return str;
        }
    }
}
